package dao;

import java.util.ArrayList;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import dialog.DlgConsultCity;

public class CityDAO {
	private EntityManager em;
	
	public CityDAO(EntityManager em) {
		this.em = em;
	}
	
	public void updateEntityManager(EntityManager em){
		this.em = em;
	}
	
	public City searchCity(String city){
		
		City citySearch;
		try{
			int codigo = Integer.parseInt(city);
			citySearch = searchCode(codigo);
			if(citySearch == null){
				citySearch = searchName(city);
			}
		}catch(Exception e){
			citySearch = searchName(city);
		}
		
		return citySearch;
	}
	
	public City searchCode(int city){
		Query query = em.createNamedQuery("searchCityCode");
	    query.setParameter("code",city);
	    return (City) query.getSingleResult();
	}
	
	
	public City searchName(String name){
		Query query = em.createNamedQuery("searchCityName");
	    query.setParameter("name", name + "%");
	    
	     ArrayList<City> colCity = (ArrayList<City>)query.getResultList();
	    
	    if(colCity.size() == 1){
	    	return colCity.get(0);	    	
	    }else {
	    	DlgConsultCity selCity = new DlgConsultCity(colCity);
	    	
	    	return selCity.getCity();
	    }
	}
	public ArrayList<City> searchNameDirect(String city){
		Query query = em.createNamedQuery("searchCityName");
	    query.setParameter("name", city + "%");
	    
	    ArrayList<City> colCity = (ArrayList<City>)query.getResultList();
	    return colCity;
	}
	
	public boolean save(City city){
		EntityTransaction trans = em.getTransaction();
		trans.begin();

		try{
			if (em.find(City.class,city.getOID()) != null){
				em.merge(city);
			}else {
				em.persist(city);
			}
			trans.commit();
		}catch (Exception e) {
			e.printStackTrace();
			trans.rollback();
			return false;
		}
		
		em.close();
		DAOFactory.getInstance().updateEntityManager();
		
		return true;
	}	
}








